<template>
  <div>
    <div v-for="(v,index) in typeArr" :key="index" @click="message1(v)">
      <div>
        {{ v.dicName }}
        <div style="marginLeft:100px;marginTop:20px;width:900px">
          <!-- <div style="marginLeft:100px;marginTop:20px;width:900px" v-if="v.description==='files'"> -->
          <el-upload
            action="string"
            :http-request="Upload"
            list-type="picture-card"
            :before-upload="changeSelectPhoto"
            :file-list="photoList1(v)"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible">
            <Cropper
              v-if="dialogVisible"
              :dialog-image-url="dialogImageUrl"
              @emitImage="emitImage"
            />
          </el-dialog>
        </div>
      </div>
    </div>
    <div v-if="sortDialogVisible">
      <el-dialog
        title="图片排序"
        center
        :visible.sync="sortDialogVisible"
        :modal-append-to-body="false"
        width="1000px"
        :before-close="closeSortDialog"
        :close-on-click-modal="false"
      >
        <div v-for="(v,index) in typeArr" :key="index" @click="message1(v)">
          <draggable v-model="dicCodeResult[v.dicCode]" :options="{animation:500}">
            <img
              v-for="item in dicCodeResult[v.dicCode]"
              :key="item.id"
              :src="item.fileUrl"
              style="width:146px;height:146px;border-radius:6px;margin:0 10px 10px 0"
            >
          </draggable>
        </div>
        <!--  -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeSortDialog">取 消</el-button>
          <el-button type="primary" @click="submitSortAfter">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="right">
      <el-button type="primary" :disabled="canSubmitPhoto" @click="subMitPhotoList">保 存</el-button>
      <el-button type="primary" @click="sortImg">排 序</el-button>
    </div>
  </div>
</template>

<script>
const client = new OSS({
  region: 'oss-cn-shanghai',
  accessKeyId: 'LTAIxZYjNPM6pgO3',
  accessKeySecret: '11iG8LcwySD1Ryw8aT1PVrQitMNYUl',
  bucket: 'syg-photo'
})
import OSS from 'ali-oss'
import mmUrl from '~/utils/utilUrl'
import Cropper from './Cropper'
import draggable from 'vuedraggable'
export default {
  components: {
    draggable,
    Cropper
  },
  props: ['typeArr', 'dataId', '_type'],
  data() {
    return {
      sortDialogVisible: false,
      dialogImageUrl: '',
      dialogVisible: false,
      commitJava: [],
      photoList: [],
      canSubmitPhoto: true,
      dicCodeResult: {}
    }
  },
  watch: {
    '$props.dataId'(newd) {
      this.getPhoto()
    }
  },
  mounted() {
    this.getPhoto()
  },
  updated() {},
  methods: {
    submitSortAfter() {
      var submitArr = []
      this.typeArr.map(v => {
        this.dicCodeResult[v.dicCode].map((v, index) => {
          v.sort = index
          submitArr.push(v)
        })
      })
      this.$post({
        url: mmUrl.file.uploadFile,
        data: {
          items: submitArr
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: res
        })
        this.sortDialogVisible = false
        this.getPhoto()
      })
    },
    closeSortDialog() {
      this.sortDialogVisible = false
    },
    sortImg() {
      const codeArr = this.typeArr.map(v => v.dicCode)
      codeArr.forEach(v => {
        this.$set(
          this.dicCodeResult,
          v,
          this.photoList.filter(vv => v === vv.typeCode)
        )
      })
      this.sortDialogVisible = true
    },
    message1(v) {
      this.typeCode = v.dicCode
    },
    changeSelectPhoto(res) {
      if (!res.type.includes('image')) {
        this.$message.error('只能上传图片文件')
        return false
      }
    },
    photoList1(res) {
      this.photoList.map(v => (v.url = v.fileUrl))
      return this.photoList.filter(v => res.dicCode === v.typeCode)
    },
    handlePictureCardPreview(file) {
      const newSourceFileUrl = client.signatureUrl(`${file.sourceFileName}`, {
        response: {
          'content-disposition': `attachment; filename=${file.sourceFileName}`
        }
      })
      this.selectImage = file
      this.dialogImageUrl = newSourceFileUrl
      this.dialogVisible = true
    },
    emitImage(data) {
      const that = this
      client.put(that.selectImage.sourceFileName, data).then(res => {
        const newSourceFileUrl = client.signatureUrl(`${res.name}`, {
          response: {
            'content-disposition': `attachment; filename=${res.name}`
          }
        })
        that.dialogVisible = false
        const result = JSON.parse(JSON.stringify(that.selectImage))
        if (result.id !== 'string') {
          result.ident = 2 // 有问题需要将修改的ident变成2
        }
        that.photoList.forEach((v, index) => {
          if (v.sourceFileName === that.selectImage.sourceFileName) {
            that.photoList[index].url = res.url
            that.photoList[index] = result
            that.$nextTick(() => {
              // 根据res.url生成一个新的本地文件文件流替换即可
              that.photoList[index].url = newSourceFileUrl
            })
          }
        })
        that.commitJava.forEach((v, index) => {
          if (v.sourceFileName === that.selectImage.sourceFileName) {
            that.commitJava[index] = result
          }
        })
        that.canSubmitPhoto = false
      })
    },
    subMitPhotoList() {
      this.canSubmitPhoto = true
      const result = this.commitJava.some(v => !v.ident === false)
      if (!result) {
        this.$message.error('您没有做出任何修改')
        return false
      }
      this.commitJava.forEach((v, index) => {
        if (v.id === 'string' && v.ident === 3) {
          this.commitJava.splice(index, 1)
        }
      })
      const codeArr = this.typeArr.map(v => v.dicCode)
      const arrClone = {}
      codeArr.forEach(v => {
        arrClone[v] = []
        this.commitJava.forEach(vv => {
          if (vv.typeCode === v) {
            arrClone[v].push(vv)
          }
        })
      })
      const finalArr = []
      codeArr.forEach(v => {
        arrClone[v].forEach((vv, index) => {
          if (vv.ident !== 3) {
            vv.sort = index
          }
          finalArr.push(vv)
        })
      })
      this.$post({
        url: mmUrl.file.uploadFile,
        data: {
          items: finalArr
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: res
        })
        this.getPhoto()
      })
    },
    handleRemove(file, fileList) {
      this.canSubmitPhoto = false
      this.commitJava.forEach(v => {
        if (v.sourceFileName === file.sourceFileName) {
          v.ident = 3
        }
      })
      this.photoList.forEach((v, index) => {
        if (v.sourceFileName === file.sourceFileName) {
          this.photoList.splice(index, 1)
        }
      })
    },
    getPhoto() {
      this.photoList = []
      this.commitJava = []
      this.$post({
        url: mmUrl.file.getfiles,
        data: {
          dataId: this.dataId
        }
      }).then(res => {
        this.photoList = JSON.parse(JSON.stringify(res))
        this.commitJava = JSON.parse(JSON.stringify(res))
      })
    },
    Upload(file) {
      const fileTypeErrorTips = file.file.type.includes('image')
      if (!fileTypeErrorTips) {
        this.$message.error('不能传递非图片类型文件')
        return false;
      }
      if(file.file.size /1024 > 500){
        this.$message.error('请上传不大于500KB的图片文件')
        return false;
      }
      const that = this
      const javaSize = (file.file.size / 1024).toFixed(2)
      const javaDateType = '.' + file.file.type.split('/')[1]
      const fileName = file.file.name
      const sourceFileName = 'photo-' + fileName + '-' + Date.parse(new Date())
      const uid = file.file.uid
      client.put(sourceFileName, file.file).then(res => {
        const newImageInfo = {
          dataId: that.dataId,
          dataType: that._type,
          extName: javaDateType,
          fileName: fileName,
          fileType: 0,
          fileUrl: res.url,
          id: 'string',
          ident: 1,
          size: javaSize,
          sort: 0,
          sourceFileName: sourceFileName,
          typeCode: that.typeCode,
          uid: uid
        }
        that.photoList.push(newImageInfo)
        that.commitJava.push(newImageInfo)
        that.canSubmitPhoto = false
      })
    }
  }
}
</script>

<style>
</style>
